import ctypes
import ctypes.wintypes
import time
import sys

# 加载DLL
try:
    dll = ctypes.WinDLL('./cmake-build-debug-visual-studio/Debug/libdxgidup.dll')
    print("成功加载DLL")
except OSError as e:
    print(f"无法加载DLL: {e}")
    sys.exit(1)

# 定义函数签名
dll.DupInit.argtypes = [ctypes.c_int, ctypes.c_int]
dll.DupInit.restype = ctypes.c_int

dll.DupShutdown.argtypes = []
dll.DupShutdown.restype = None

dll.DupIsReady.argtypes = []
dll.DupIsReady.restype = ctypes.c_int

dll.DupGetPixel.argtypes = [ctypes.c_int, ctypes.c_int]
dll.DupGetPixel.restype = ctypes.c_uint

# 性能测试参数
test_points = [
    (100, 100),
    (500, 300),
    (1000, 500),
    (1500, 800),
    (1920, 1080)
]

iterations = 10000  # 总测试次数

def main():
    print("DXGI单点取色性能测试 (Python版)")
    print("===============================")
    
    # 初始化屏幕捕获
    print("初始化屏幕捕获...")
    if not dll.DupInit(0, 60):
        print("初始化失败")
        return -1
    
    # 等待捕获准备好
    print("等待捕获准备就绪...")
    attempts = 0
    while not dll.DupIsReady() and attempts < 100:
        time.sleep(0.05)  # 50ms
        attempts += 1
    
    if not dll.DupIsReady():
        print("捕获未能准备就绪")
        dll.DupShutdown()
        return -1
    
    print("开始性能测试...")
    
    # 执行性能测试
    start_time = time.perf_counter()
    
    for i in range(iterations):
        # 循环测试不同的点
        x, y = test_points[i % len(test_points)]
        dll.DupGetPixel(x, y)
    
    end_time = time.perf_counter()
    duration_us = (end_time - start_time) * 1_000_000  # 转换为微秒
    
    avg_time = duration_us / iterations
    ops_per_sec = 1_000_000 / avg_time if avg_time > 0 else 0
    
    print("测试结果:")
    print(f"总测试次数: {iterations}")
    print(f"总耗时: {duration_us:.0f} 微秒")
    print(f"平均每次调用耗时: {avg_time:.2f} 微秒")
    print(f"每秒操作次数: {ops_per_sec:.0f} 次/秒")
    
    # 测试不同坐标下的取色值
    print("\n各测试点颜色值:")
    for x, y in test_points:
        color = dll.DupGetPixel(x, y)
        print(f"坐标({x}, {y}) 颜色值: 0x{color:08x}")

    # 关闭屏幕捕获
    dll.DupShutdown()
    
    print("\n性能测试完成。")

    return 0

if __name__ == "__main__":
    main()